package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(UserLoginDTO dto) {
        // 通过HTTPClient构造登录校验请求
        // 创建一个Map对象，用于存储参数
        Map<String, String> paramMap=new HashMap<>();
        // 将微信的appid放入Map中
        paramMap.put("appid",weChatProperties.getAppid());
        // 将微信的secret放入Map中
        paramMap.put("secret",weChatProperties.getSecret());
        // 将微信的js_code放入Map中
        paramMap.put("js_code",dto.getCode());
        // 将微信的grant_type放入Map中，授权类型为authorization_code
        paramMap.put("grant_type","authorization_code");
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        log.info("res：{}", res);
        // 解析登录校验返回结果。获取openId
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        if (openid == null)
        {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 判断是否为新用户，根据openid查询user表
        User user = userMapper.selectByOpenid(openid);

        //如果是新用户，初始化用户数据到user表
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            user.setName(openid.substring(0, 5));
            userMapper.insert(user);
        }
        //如果不是新用户，直接返回user对象数据
        return user;
    }
}
